package com.tcwlkj.uuService.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.makeramen.roundedimageview.RoundedImageView;
import com.tcwlkj.uuService.MyApp;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.enums.CheckStatus;
import com.tcwlkj.uuService.model.AddressModel;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.QrCodeModel;
import com.tcwlkj.uuService.model.UpdateMessage;
import com.tcwlkj.uuService.ui.PushOrderActivity;
import com.tcwlkj.uuService.ui.login.IDcertification;
import com.tcwlkj.uuService.utils.ChcheUtils;
import com.tcwlkj.uuService.utils.CommomDialog;
import com.tcwlkj.uuService.utils.Const;
import com.tcwlkj.uuService.utils.EventCenter;
import com.tcwlkj.uuService.utils.MyRefresh;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.ToastUtil;
import com.tcwlkj.uuService.widget.MarqueeText;

import org.greenrobot.eventbus.EventBus;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * Created by Administrator on 2017/9/30 0030.
 */

public class RealtimeOrder_Fragment extends BaseFragment {

    @Bind(R.id.btn_start_working)
    TextView btn_start_working;
    @Bind(R.id.recommend_runman_iv)
    ImageView recommend_runman_iv;
    @Bind(R.id.recommend_user_iv)
    ImageView recommend_user_iv;
    @Bind(R.id.img_start_work)
    ImageView img_start_work;
    @Bind(R.id.lay_start_work_fragment)
    FrameLayout lay_start_work_fragment;
    @Bind(R.id.tv_over_work)
    TextView tv_over_work;
    @Bind(R.id.tv_current_address)
    MarqueeText tv_current_address;
    @Bind(R.id.btn_refresh_current)
    Button btn_refresh_current;
    @Bind(R.id.shenfen_yanzheng)
    RelativeLayout shenfen_yanzheng;
    @Bind(R.id.tishi_information)
    TextView tishi_information;
    @Bind(R.id.checkid)
    TextView checkid;
    @Bind(R.id.img_user_head_current)
    RoundedImageView img_user_head_current;
    @Bind(R.id.refresh)
    TwinklingRefreshLayout refresh;
    @Bind(R.id.ll_real_main)
    LinearLayout ll_real_main;

    @Bind(R.id.tv_orders_current)
    TextView tv_orders_current;
    @Bind(R.id.tv_money_current)
    TextView tv_money_current;


    @Override
    protected int getLayout() {
        return R.layout.fragment_realtime;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_current_address.setEllipsize(null);
        tv_current_address.startScroll();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        MyRefresh.getInstance().getoneMusic(refresh, false);
        getRprCode();//获取二维码
        refresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                getRprCode();
                ChangeState();
                EventBus.getDefault().post(new EventCenter<String>(1002, "首界面刷新"));
                refresh.finishRefreshing();
            }
        });
    }

//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        if(isVisibleToUser){
//            Const.isJpushTag=true;
//        }else {
//            Log.d("JpushTag","00000");
//        }
//    }

    @Override
    public void onStart() {
        super.onStart();
        if (Const.isJpushTag) {
            Const.JpushTag = true;
            Log.d("JpushTag", "onStart");
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Const.JpushTag = false;
        Log.d("JpushTag", "onStop");
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {
        super.onEventComing(eventCenter);
        switch (eventCenter.getEventCode()) {
            case 100:
                ChangeState();
                // Glide.with(this).load(ChcheUtils.getInstance().getDriverDetailModel().getPhotos().get(0).getSamllPhoto()).error(R.mipmap.iv_touxiang).into(img_user_head_current);
                break;
            case 101:
                getCity(false);
                break;
            case 55:
                if (Const.JpushTag) {
                    UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
                    Intent intent = new Intent(getActivity(), PushOrderActivity.class);
                    intent.putExtra("OrderDetail", updateMessage.getMessage());
                    intent.putExtra("type", updateMessage.getType());
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    //状态改变
    private void ChangeState() {
        if (ChcheUtils.getInstance().getDriverDetailModel() == null)
            return;
        int state = ChcheUtils.getInstance().getDriverDetailModel().getBase().getState();
        Glide.with(this).load(ChcheUtils.getInstance().getDriverDetailModel().getPhotos().get(0).getSamllPhoto()).error(R.mipmap.iv_touxiang).into(img_user_head_current);
        tv_orders_current.setText(ChcheUtils.getInstance().getDriverDetailModel().getLast().getNowOrderNum());
        tv_money_current.setText(ChcheUtils.getInstance().getDriverDetailModel().getLast().getNowIncome());
        switch (CheckStatus.get(state)) {
            case Apply://已申请
                shenfen_yanzheng.setVisibility(View.VISIBLE);
                checkid.setEnabled(true);
                checkid.setText("身份验证");
                tishi_information.setText("您已注册成功，请进行身份验证");
                break;
            case Signed://已签约
                shenfen_yanzheng.setVisibility(View.GONE);
                break;
            case SubmitAuth://待审核
                shenfen_yanzheng.setVisibility(View.VISIBLE);
                checkid.setText("等待审核 ");
                checkid.setEnabled(false);
                tishi_information.setText("你的资料正在审核，请耐心等待");
                break;
            case AuditNo://审核失败
                shenfen_yanzheng.setVisibility(View.VISIBLE);
                checkid.setText("身份验证");
                checkid.setEnabled(true);
                tishi_information.setText("你的资料未审核通过，请再次提交");
                break;
            case Auditsign://待签约
                checkid.setText("培训地址");
                shenfen_yanzheng.setVisibility(View.GONE);
                checkid.setEnabled(true);
                tishi_information.setText("您的资料审核通过，请参加培训");
                break;
            case Frozen://已冻结
                break;
            case Cancle://已注销
                break;
        }
        if (PreferencesUtils.getInt(MyApp.getContext(), PreferencesUtils.getString(MyApp.getContext(), "userID") + "work", 5) == 1 || PreferencesUtils.getInt(MyApp.getContext(), PreferencesUtils.getString(MyApp.getContext(), "userID") + "work", 5) == 2) {//开工
            onWork();
        } else if (PreferencesUtils.getInt(MyApp.getContext(), PreferencesUtils.getString(MyApp.getContext(), "userID") + "work", 5) == 5) {//收工
            offWork();
        }
    }

    @OnClick({R.id.tv_over_work, R.id.btn_start_working, R.id.btn_refresh_current, R.id.checkid})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_over_work:
                CommomDialog work_dialog = new CommomDialog(getContext(), R.style.dialog, "", new CommomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                    }
                }, new CommomDialog.OnCancelsListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (!PreferencesUtils.getString(MyApp.getContext(), "oridIdList").equals("")) {
                            ToastUtil.getInstance().show("您有未完成的订单，请先去完成");
                        } else {
                            updateWork("5");
                        }
                    }
                }).setTitle("确定收工吗？").setNegativeButton("确定收工").setPositiveButton("再赚一会");
                work_dialog.show();
                work_dialog.setimageVisibility(true);
                work_dialog.setTitleVisibility(false);
                work_dialog.setTextColor();
                break;
            case R.id.btn_start_working:
                if (ChcheUtils.getInstance().getDriverDetailModel() == null) {
                    return;
                }
                int state = ChcheUtils.getInstance().getDriverDetailModel().getBase().getState();
                switch (CheckStatus.get(state)) {
                    case Apply://已申请
                        new CommomDialog(getActivity(), R.style.dialog, "请先进行身份验证", new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                                startActivity(new Intent(getActivity(), IDcertification.class));
                            }
                        }).setTitle("提示").setPositiveButton("身份验证").show();
                        break;
                    case Signed://已签约
                        updateWork("1");
                        break;
                    case SubmitAuth://待审核
                        new CommomDialog(getActivity(), R.style.dialog, "请等待审核", new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                            }
                        }).setTitle("提示").show();
                        break;
                    case AuditNo://审核失败
                        new CommomDialog(getActivity(), R.style.dialog, "审核失败，请重新进行验证", new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                                startActivity(new Intent(getActivity(), IDcertification.class));
                            }
                        }).setTitle("提示").setPositiveButton("身份验证").show();
                        break;
                    case Auditsign://待签约
                        updateWork("1");
                        break;
                    case Frozen://已冻结
                        new CommomDialog(getActivity(), R.style.dialog, "您的账户已被冻结", new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                            }
                        }).setTitle("提示").show();
                        break;
                    case Cancle://已注销
                        new CommomDialog(getActivity(), R.style.dialog, "您的账户已被注销", new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                            }
                        }).setTitle("提示").show();
                        break;
                }
                break;
            case R.id.btn_refresh_current:
                getCity(true);
                break;
            case R.id.checkid:
                int checkState = ChcheUtils.getInstance().getDriverDetailModel().getBase().getState();
                switch (CheckStatus.get(checkState)) {
                    case Apply:
                    case AuditNo:
                        startActivity(new Intent(getActivity(), IDcertification.class));
                        break;
                    case Auditsign:
                        new CommomDialog(getActivity(), R.style.dialog, "聚光中心", new CommomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                            }
                        }).setTitle("培训地址").show();
                        break;
                }
                //
                break;
        }
    }

    /**
     * 开工收工接口
     */
    private void updateWork(String nval) {
        Call<CommonResponse> httpResultCall = RetrofitUtils.getRequest(getActivity(), false).updateWork("wstate", PreferencesUtils.getString(MyApp.getContext(), "userID"), nval);
        httpResultCall.enqueue(new HttpCallBack<CommonResponse>() {
            @Override
            public void onSuccess(Object t) {
                if (nval.equals("1")) {//开工
                    PreferencesUtils.putInt(MyApp.getContext(), PreferencesUtils.getString(MyApp.getContext(), "userID") + "work", 1);
                    onWork();
                } else if (nval.equals("5")) {//收工
                    PreferencesUtils.putInt(MyApp.getContext(), PreferencesUtils.getString(MyApp.getContext(), "userID") + "work", 5);
                    offWork();
                }
            }

            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    updateWork(nval);
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }

    /**
     * 获取二维码
     */
    public void getRprCode() {
        Call<CommonResponse<QrCodeModel>> httpResultCall = RetrofitUtils.getRequest(getActivity(), false).rqrcode(Long.parseLong(PreferencesUtils.getString(MyApp.getContext(), "userID")));
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<QrCodeModel>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<QrCodeModel> commonResponse = (CommonResponse<QrCodeModel>) t;
                Glide.with(RealtimeOrder_Fragment.this).load(commonResponse.getData().getDriver()).error(R.mipmap.iv_code).into(recommend_runman_iv);
                Glide.with(RealtimeOrder_Fragment.this).load(commonResponse.getData().getUser()).error(R.mipmap.iv_code).into(recommend_user_iv);
                PreferencesUtils.putString(MyApp.getContext(), "runManCode", commonResponse.getData().getDriver());
                PreferencesUtils.putString(MyApp.getContext(), "userCode", commonResponse.getData().getUser());
                ChangeState();

            }

            @Override
            public void onFail(int code, String message) {

                if (code == 40104) {
                    getRprCode();
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }

    //开工
    public void onWork() {
        lay_start_work_fragment.setClickable(false);
        Animation operatingAnim = AnimationUtils.loadAnimation(getContext(), R.anim.rotate);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
        img_start_work.setAnimation(operatingAnim);
        btn_start_working.setText("听单中");
        tv_over_work.setVisibility(View.VISIBLE);
        tv_over_work.setClickable(true);
    }

    //收工
    public void offWork() {
        img_start_work.clearAnimation();
        btn_start_working.setText("开始\n接单");
        tv_over_work.setVisibility(View.GONE);
        tv_over_work.setClickable(false);
//      开始接单点击时间
        lay_start_work_fragment.setClickable(true);
    }

    //根据经纬度获取位置
    public void getCity(boolean flag) {
        Call<CommonResponse<AddressModel.ResultBean>> httpResultCall = RetrofitUtils.getRequest(getContext(), flag).getCityAddress(ChcheUtils.getInstance().getLocationModel().getLng() + "", ChcheUtils.getInstance().getLocationModel().getLat() + "");
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<AddressModel.ResultBean>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<AddressModel.ResultBean> addressModel = (CommonResponse<AddressModel.ResultBean>) t;
                tv_current_address.setText(addressModel.getData().getFormatted_address());
            }

            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    getCity(flag);
                } else {
                    tv_current_address.setText("暂无位置信息");
                }
            }
        });
    }


}
